<template>
  <div class="container">
    <div class="app-container">
         <!-- 精选题库 -->
    <el-card shadow="never">
      <!-- 表头按钮(新增精选题库) -->
       <!-- ◆头部新增题库按钮区域 -->
        <div class="btn_wrapper">
          <span style="font-size: 12px; color: pink"
            >说明：目前支持学科和关键字条件筛选</span
          >
          <el-button
            @click="addNewQuestionHandler"
            class="el-button el-button--success el-button--small"
            ><i class="el-icon-edit"></i><span>新增试题</span></el-button
          >
        </div>
      <!-- form表单 -->
        <!-- ◆表单筛选区域 -->
        <el-form ref="filterRef" class="filterform-style" :model="filterForm">
          <el-form-item
            label="学科"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select
              @change="subjChangeHandler"
              v-model="filterForm.subjectID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in subject"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="二级目录"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select v-model="filterForm.catalogID" placeholder="请选择">
              <el-option
                v-for="item in catalog"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="标签"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select v-model="filterForm.tags" placeholder="请选择">
              <el-option
                v-for="item in tags"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="关键字"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-input
              v-model="filterForm.keyword"
              type="text"
              placeholder="根据题干搜索"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="试题类型"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select v-model="filterForm.questionType" placeholder="请选择">
              <el-option
                v-for="item in questionType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="难度"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select v-model="filterForm.difficulty" placeholder="请选择">
              <el-option
                v-for="item in difficulty"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="方向"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select v-model="filterForm.direction" placeholder="请选择">
              <el-option
                v-for="item in direction"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="录入人"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select v-model="filterForm.creatorID" placeholder="请选择">
              <el-option
                v-for="item in creator"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="题目备注"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-input type="text" v-model="filterForm.remarks"></el-input>
          </el-form-item>
          <el-form-item
            label="企业简称"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-input type="text" v-model="filterForm.shortName"></el-input>
          </el-form-item>
          <el-form-item
            label="城市"
            style="height: 50px; width: 25%"
            label-width="80px"
          >
            <el-select
              v-model="filterForm.province"
              placeholder="请选择"
              style="width: 50%"
              @change="cityChangeHandler"
            >
              <el-option
                v-for="(item, index) in provinces"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              v-model="filterForm.city"
              placeholder="请选择"
              style="width: 50%"
            >
              <el-option
                v-for="(item, index) in citys"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            style="height: 50px; width: 25%; text-align: right"
            label-width="80px"
          >
            <el-button
              class="el-button el-button--default el-button--small"
              @click="clearFilterHandler"
              >清除</el-button
            >
            <el-button
              class="el-button el-button--primary el-button--small"
              @click="searchQuesHandler"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>

      <!-- 标签跳转 -->
      <el-tabs v-model="activeName" type="card"  @tab-click="handleClick">
        <el-tab-pane label="全部" name="first" ></el-tab-pane>
        <el-tab-pane label="待审核" name="second"></el-tab-pane>
        <el-tab-pane label="已审核" name="third"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="fourth"
          ></el-tab-pane
        >
      </el-tabs>
      <!-- 灰色消息提示 -->
      <el-alert class="alert"
        :title="`共 ${this.total} 条记录`"
        type="info"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="number" label="试题编号" width="100" />
        <el-table-column prop="subject" label="学科" width="120">
        </el-table-column>
        <el-table-column prop="catalog" label="目录" width="120">
        </el-table-column>
        <el-table-column label="题型" width="120">
          <template slot-scope="scope">
            {{questionTypeHandler(scope.row.questionType)
          }}</template>
        </el-table-column>
        <el-table-column  label="题干" width="120">
          <template slot-scope="scope">
           {{ html2TextHandler(scope.row.question)}}
          </template>
        </el-table-column>
        <el-table-column  label="录入时间" width="200">
          <template slot-scope="scope" >
            {{formData(scope.row.addDate)}}
          </template>
        </el-table-column>
        <el-table-column label="难度" width="120">
          <template slot-scope="scope">{{
            difficultyHandler(scope.row.difficulty)
          }}</template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人" width="120">
        </el-table-column>
        <el-table-column label="审核状态" width="120">
          <template  slot-scope="scope">
            {{chkStateHandler(scope.row.chkState)}}
          </template>
        </el-table-column>
        <el-table-column prop="chkRemarks" label="审核意见" width="120">
        </el-table-column>
        <el-table-column prop="chkUser" label="审核人" width="120">
        </el-table-column>
        <el-table-column label="发布状态" width="120">
          <template slot-scope="scope">
            {{publishStateHandler(scope.row.publishState)}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="prevQuestionHandler(scope.row)">预览</el-button>
            <el-button type="text" size="medium"  @click="checkStateHandler(scope.row)" :disabled="scope.row.chkState==2">审核</el-button>
            <el-button type="text" size="medium"  @click="editQuesHandler(scope.row)" :disabled="scope.row.publishState==0">修改</el-button>
            <el-button type="text" size="medium"  @click="pubChoQuesHandler(scope.row)"
              >{{scope.row.publishState?'上架':'下架'}}</el-button
            >
            <el-button
              type="text"
              size="medium"
              @click="deleChoQuesHandler(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <PageTools
          :paginationPage="queryObj.page"
          :paginationPagesize="queryObj.pagesize"
          :total="total"
          @pageChange="handleCurrentChange"
          @pageSizeChange="handleSizeChange"
        >
        </PageTools>
      </div>
    </el-card>
    <!--  题目审核-->
    <el-dialog :visible.sync="showQuesCheDia" title="题目审核" width="30%" >
      <QuesCheDia v-if="showQuesCheDia" ref="QuesCheDiaRef" @cancel="showQuesCheDia=false" :row="row" @success="successHandler"></QuesCheDia>
    </el-dialog>
    <!--精选预览 -->
     <el-Dialog :visible.sync="PreviewDiaVisible" title="题目预览" @closed="closePreviewHandler">
        <div>
          <div  class="prevheader-style" >
            <span >【题型】：{{questionTypeHandler(previeList.questionType)}}</span>
            <span >【编号】：{{previeList.id}}</span>
            <span >【难度】：{{difficultyHandler(previeList.difficulty)}}</span>
            <span >【标签】：{{previeList.tags}}</span>
            <span >【学科】：{{previeList.subjectName}}</span>
            <span >【目录】：{{previeList.directoryName}}</span>
            <span >【方向】：{{previeList.direction}}</span>
          </div>
          <!-- 分割线 -->
          <el-divider></el-divider>
          <div>
            <p>【题干】: </p>
            <p style="color:blue">{{html2TextHandler(previeList.question)}}</p>
            <p >{{questionTypeHandler(previeList.questionType)}}题 选项：(以下选中的答案为正确答案)</p>
          </div>
          <div>
             <div  v-for="(item,index) in previeList.options" :key="index">
                 <el-checkbox v-model="item.isRight"  disabled :checked="Boolean(item.isRight)" >{{item.code}}.{{item.title}}</el-checkbox>
            </div>
          </div>
          <!-- 分割线 -->
          <el-divider></el-divider>
          <div>
            <div style="margin-bottom:20px">
              <span>【参考答案】：</span
              ><el-button class="el-button el-button--danger el-button--small"
              @click="showVideo=!showVideo"
                ><span>视频答案预览</span></el-button
              >
            </div>
            <div v-if="showVideo" class="video-style" ><video  :src="previeList.videoURL"  autoplay controls></video></div>
          </div>
          <!-- 分割线 -->
          <el-divider></el-divider>
          <div>【答案解析】: {{html2TextHandler(previeList.answer)}}</div>
          <!-- 分割线 -->
          <el-divider></el-divider>
          <div>【题目备注】: {{previeList.remarks}}</div>
          <div style="text-align:right">
            <el-button class="el-button el-button--primary el-button--medium"
            @click="PreviewDiaVisible=false"
              >关闭</el-button
            >
          </div>
        </div>
      </el-Dialog>
    </div>

  </div>
</template>

<script>
// 导入获取精选题库列表,精选题库删除,精选题库上下架,试题审核、精选题库详情的接口函数
import { choice, choiceDel, choicePublish, choiceCheck, detail } from '@/api/hmmm/questions'
// 导入 html 转 text 的工具函数
import { html2Text } from '@/utils'
// 下包 dayjs 并导入 用于（格式化时间）
import dayjs from 'dayjs'
// 导入 分页组件
import PageTools from '@/module-hmmm/components/PageTools/page-tools.vue'
// 导入循环城市和地区的函数
import { provinces, citys } from '@/api/hmmm/citys'
// 导入 难度、题型、方向数据(筛选需要)
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
// 导入 获取简单学科数据的接口函数
import { subjSimple } from '@/api/hmmm/subjects'
// 导入 获取录入人列表的接口函数
import { userSimple } from '@/api/base/users'
// 导入获取标签的简单列表的接口函数
import { tagSimple } from '@/api/hmmm/tags'
// 导入获取二级目录列表的接口函数
import { cataSimple } from '@/api/hmmm/directorys'
// 导入审核对话框
import QuesCheDia from '@/module-hmmm/components/questions-check.vue'
export default {
  components: {
    PageTools,
    QuesCheDia
  },
  data () {
    return {
      tableData: [], // 精选题库数据列表
      total: 0,
      // 查询参数
      queryObj: {
        page: 1,
        pagesize: 10
      },
      activeName: 'first',
      msg: '', // 上下架的变量
      // 筛选表单
      filterForm: {
        subjectID: '', // 学科
        catalogID: '', // 二级目录
        keyword: '', // 关键字
        creatorID: '', // 录入人
        difficulty: '', // 难度
        questionType: '', // 试题类型
        tags: '', // 标签
        direction: '', // 方向
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        province: '', // 城市
        city: '' // 区域
      },
      subject: [], // 学科列表数组
      catalog: [], // 二级目录列表数据
      tags: [], // 标签列表数组
      difficulty, // 试题难度数组
      questionType, // 试题类型数组
      direction, // 试题方向数组
      creator: [], // 录入人数组
      provinces: [], // 省市数组
      citys: [], // 对应的区域数组
      showQuesCheDia: false, // 审核对话框状态
      row: {}, // 父传子
      PreviewDiaVisible: false,
      previeList: {}, // 预览详情数据
      showVideo: false
    }
  },
  created () {
    // ◆触发 methods 定义的 获取精选题库列表函数
    this.getQuestionsChoice()
    // ◆触发 methods 中的 下载省市的 函数
    this.loadProvincesHandler()
    // ◆触发 methods 中的 下载学科列表的函数
    this.loadSubjectHandler()
    // ◆触发 methods 中的 下载用户简单信息的函数(获取录入人)
    this.loadUserHandler()
  },
  methods: {
    // ◆获取精选题库列表
    async getQuestionsChoice () {
      // 1.发送ajajx
      const res = await choice(this.queryObj)
      console.log(res, '精选题库列表111')
      // 2.赋值表格
      this.tableData = res.data.items
      // 3.赋值几条消息
      this.total = res.data.counts
    },
    // ◆封装试题类型转化函数
    questionTypeHandler (num) {
      if (Number(num) === 1) {
        return '单选'
      } else if (Number(num) === 2) {
        return '多选'
      } else if (Number(num) === 3) {
        return '简答'
      }
    },
    // ◆封装试题难度转化函数
    difficultyHandler (num) {
      if (Number(num) === 1) {
        return '简单'
      } else if (Number(num) === 2) {
        return '一般'
      } else if (Number(num) === 3) {
        return '困难'
      }
    },
    // ◆封装格式化时间函数
    formData (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // ◆定义HTML 转 text 的函数(题干函数)
    html2TextHandler (html) {
      return html2Text(html)
    },
    // ◆封装发布状态的函数
    publishStateHandler (num) {
      if (Number(num) === 2) {
        return '待发布'
      } else if (Number(num) === 0) {
        return '已发布'
      } else if (Number(num) === 1) {
        return '已下架'
      }
    },
    // ◆封装审核状态的函数
    chkStateHandler (num) {
      if (Number(num) === 0) {
        return '待审核'
      } else if (Number(num) === 1) {
        return '通过'
      } else if (Number(num) === 2) {
        return '拒绝'
      }
    },
    // ◆标签跳转
    async  handleClick (tab, event) {
    // chkState 待审核 0   已审核 1  已拒绝 2
      if (this.activeName === 'first') {
        this.queryObj = {
          page: 1,
          pagesize: 10
        }
      }
      if (this.activeName === 'second') {
        this.queryObj.chkState = 0
      }
      if (this.activeName === 'third') {
        this.queryObj.chkState = 1
      }
      if (this.activeName === 'fourth') {
        this.queryObj.chkState = 2
      }
      this.getQuestionsChoice()// 直接调用
    // const res = await choice(this.queryObj)
    // console.log(res, '标签切换的精选列表')
    // // 2.赋值表格
    // this.tableData = res.data.items
    // // 3.赋值几条消息
    // this.total = res.data.counts
    },
    // ◆每页显示信息条数
    handleSizeChange (val) {
    // 1.修改每页显示条数
      this.queryObj.pagesize = val
      // 2.默认跳转到第一页
      this.queryObj.page = 1
      // 3.重新渲染精选题库列表
      this.getQuestionsChoice()
    },
    // ◆进入某一页
    handleCurrentChange (val) {
    // 1.修改显示页面
      this.queryObj.page = val
      console.log(444)
      // 2.重新渲染精选题库列表
      this.getQuestionsChoice()
    },
    // ◆点击了修改按钮
    editQuesHandler (row) {
      console.log(row, '点击了修改按钮精选题库123')
      // 跳转到试题试题录入页面
      this.$router.push({ name: 'questions-new', query: { id: row.id } })
    // 后面跳到裴雨轩的页面
    },
    // ◆◆◆点击新增精选题库
    addNewQuestionHandler () {
    // 跳到录入试题页面准备新增(路由跳转)
      this.$router.push({ name: 'questions-new' })
    // 后面由裴雨轩做
    },
    // ◆点击了删除精选题库按钮
    deleChoQuesHandler (row) {
    // 1.弹出提示框
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
      // 2.发送ajajx
        const res = await choiceDel(row)
        console.log(res, '删除了精选题库11')
        if (res.status === 200) {
        // 3.成功提示
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 7.删除功能优化◆◆
          if (this.tableData.length === 1 && this.queryObj.page > 1) {
            this.queryObj.page--
          }
          // 4.重新获取精选题库列表
          this.getQuestionsChoice()
        } else {
        // 5.删除失败提示
          this.$message({
            type: 'info',
            message: '删除失败!'
          })
        }
      }).catch(() => {
      // this.$message({
      //   type: 'info',
      //   message: '已取消删除'
      // })
      })
    },
    // ◆点击了预览试题详情
    async prevQuestionHandler (row) {
      console.log(row, 888888)
      // 1.展示预览弹框
      this.PreviewDiaVisible = true
      // 2.发送ajax，获取详情
      const { data: res } = await detail(row)
      console.log(res, '基础题库详情333')
      this.previeList = res
    },
    // ◆点击了关闭预览
    closePreviewHandler () {
      this.PreviewDiaVisible = false
      this.showVideo = false
    },
    // ◆点击修改审核状态
    async  checkStateHandler (row) {
      console.log(row)
      // 1打开弹框
      this.showQuesCheDia = true
      // 2.赋值（父传子）
      this.row = row
    // 3.强制父传子
    // await this.$nextTick(
    //   this.$refs.QuesCheDiaRef.chkForm = row
    // )
    },
    // ◆点击确认修改审核状态
    async successHandler (data) {
      console.log(data, '99188193')
      const res = await choiceCheck(data)
      console.log(res, '试题审核9999')
      // 审核成功
      if (res.status === 200) {
      // 1.成功提示
        this.$message({
          type: 'success',
          message: '修改审核状态成功!'
        })
        // 重新发请求获取最新数据
        this.getQuestionsChoice()
        // 关闭对话框
        this.showQuesCheDia = false
      } else {
      // 3.成功提示
        this.$message({
          type: 'info',
          message: '修改审核状态失败!'
        })
      }
    },
    // ◆点击上下架精选试题
    pubChoQuesHandler (row) {
      console.log(row, 199)
      console.log(row.publishState, '上下架')
      // 判断上下架状态
      // 1.定义弹出框显示上架 or 下架
      row.publishState ? this.msg = '上架' : this.msg = '下架'
      // 2.弹出提示框
      this.$confirm(`此操作将${this.msg}该试题, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
      // 3.发送ajajx
        const res = await choicePublish(row)
        console.log(res, `${this.msg}啦111`)
        // 4.判断状态码
        if (res.status === 200) {
        // 5.上架 or 下架成功
          this.$message({
            type: 'success',
            message: `${this.msg}成功!`
          })
          // 6.修改上架 or 下架的文字显示(转为 number 类型)
          row.publishState = Number(!row.publishState)
        } else {
        // 7.上架 or 下架 失败
          this.$message({
            type: 'info',
            message: `${this.isUpdate}失败!`
          })
        }
      }).catch(() => {
      // 取消上架(不做处理)
      // this.$message({
      //   type: 'info',
      //   message: '已取消删除'
      // })
      })
    },
    // ◆获取省市列表的函数
    loadProvincesHandler () {
      this.provinces = provinces()
      console.log(this.provinces, 9999999912)
    },
    // ◆获取对应区域列表的函数(触发城市的 change 事件，才会出来区域)
    cityChangeHandler () {
    // 1.赋值给省市对应的区域
      this.citys = citys(this.filterForm.province)
    },
    // ◆获取学科列表函数
    async loadSubjectHandler () {
    // 1.发送ajax ,获取学科列表
      const res = await subjSimple()
      console.log(res, '00000')
      // 2.赋值给学科列表
      this.subject = res.data
    },
    // ◆ 获取二级目录列表(触发了学科的 change 事件才可能会有二级目录)
    changeCataLogHandler () {},
    // ◆获取录入人列表的函数
    async loadUserHandler () {
    // 1.发送ajax
      const { data: res } = await userSimple(this.filterForm.keyword)
      console.log(res, '获取录入人11')
      // 2.赋值给录入人列表
      this.creator = res
    },
    // ◆获取二级目录、标签列表的函数(学科选择了以后，才会触发它们)
    async subjChangeHandler () {
    // *1.二级目录(注意传 ID 的形式：subjectID: this.filterForm.subjectID )
    // 1.1发送ajajx 获取 二级目录
      const { data: res1 } = await cataSimple({
        subjectID: this.filterForm.subjectID
      })
      console.log(res1, '二级目录')
      // console.log(this.filterForm.subjectID)
      // 1.2赋值给 catalog
      this.catalog = res1
      // *2.标签
      // 2.1.发送ajajx
      const { data: res2 } = await tagSimple(this.filterForm.subjectID)
      console.log(res2, '这是获取的标签11121')
      // 2.2赋值给标签列表
      this.tags = res2
    },
    // ◆点击了搜索筛选数据按钮
    async searchQuesHandler () {
      console.log(this.requestParams, '筛选前的参数123')
      // 把筛选出来的数据 赋值给 查询参数
      for (const key in this.filterForm) {
        if (this.filterForm[key] !== '') {
          this.queryObj[key] = this.filterForm[key]
        }
      }
      // console.log(this.filterForm, '删除了对象中的空属性')
      // 把筛选出来的值赋值给查询参数
      // this.requestParams = Object.assign(this.filterForm, this.requestParams)
      // console.log(this.requestParams, '筛选222')
      console.log(this.queryObj, '筛选条件222')
      // 重新获取筛选后的精选题库列表
      this.getQuestionsChoice()
    },
    // ◆点击清除表单筛选按钮
    clearFilterHandler () {
    // this.$refs.filterRef.resetFields()???为什么不起作用
    // 1.清除了表单
      this.filterForm = {
        subjectID: '', // 学科
        catalogID: '', // 二级目录
        keyword: '', // 关键字
        creatorID: '', // 录入人
        difficulty: '', // 难度
        tags: '', // 标签
        questionType: '', // 试题类型
        direction: '', // 方向
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        province: '', // 城市
        city: '' // 区域
      }
      // 2.重新赋值查询参数
      this.queryObj = {
        page: 1,
        pagesize: 10
      }
      // 3.重新加载精选题库列表
      this.getQuestionsChoice()
    }
  }
}
</script>

<style scoped lang='scss'>
// 表头按钮的样式
.btn_wrapper {
  display: flex;
  margin-bottom: 15px;
  justify-content: space-between;
  align-items: center;
}
// 表单的样式
.filterform-style {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}
// 分页的样式
.pagination {
  margin-top: 10px;
  text-align: right;
}

// 显示消息几条的样式
.alert {
  margin: 10px 0px;
}
// 预览区域
.prevheader-style {
  display:flex;
  flex-wrap:wrap;
  span {
  width:25%;
  margin-right:15px
}
}

</style>
